package com.superatom.concurrent.basic.join;

/**
 * 一个线程加入到另外一个线程中，可以试图模拟等待另一个线程
 * 后面使用CyclicBarrier更方便
 */
class Sleeper extends Thread {
    private int duration;
    public Sleeper(String name, int sleepTime){
        super(name);
        duration = sleepTime;
        start();
    }

    public void run(){
        try {
            sleep(duration);
        } catch (InterruptedException e) {
            System.out.println(getName() + " was interrupted. "
                    + "isInterrupted(): " + isInterrupted());
            return;
        }

        System.out.println(getName() + " has awakened");
    }
}

class Joiner extends Thread {
    private Sleeper sleeper;

    public Joiner(String name, Sleeper sleeper){
        super(name);
        this.sleeper = sleeper;
        start();
    }

    @Override
    public void run() {
        try {
            // 线程sleeper加入，此时，当前线程会挂起，等待加入的线程执行完毕才继续执行
            sleeper.join();
        } catch (InterruptedException e) {
            System.out.println("Interrupted");
        }

        System.out.println(getName() + " join completed");
    }
}

public class Joining {
    public static void main(String[] args) {
        Sleeper sleepy = new Sleeper("Sleepy", 1500);
        Sleeper grumpy = new Sleeper("Grumpy", 1500);

        // 首先启动sleepy线程，再启动dopey线程，并且把sleepy添加到dopey线程中
        // 那么，dopey线程就要等待sleepy执行完毕，才开始继续执行，dopey线程会被挂起
        Joiner dopey = new Joiner("Dopey", sleepy);
        Joiner doc = new Joiner("Doc", grumpy);

        grumpy.interrupt();
    }
}
